package com.example.demo22;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.demo22.domain.User;
import com.example.demo22.service.UserService;
import com.example.demo22.web.Web;

public class Register extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_phone;
    private EditText edit_password;
    private EditText edit_repassword;
    private Button button_register;

    Web web = null;
    UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        web = new Web(this);

        userService=new UserService(this);
        //Log.i("context","002"+this.toString());
    }

    private void initView() {
        edit_phone = (EditText) findViewById(R.id.edit_phone);
        edit_password = (EditText) findViewById(R.id.edit_password);
        edit_repassword = (EditText) findViewById(R.id.edit_repassword);
        button_register = (Button) findViewById(R.id.button_register);

        button_register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_register:
                submit();
                break;
        }
    }

    private void submit() {
        // validate
        String phone = edit_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "phone不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = edit_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "password不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String repassword = edit_repassword.getText().toString().trim();
        if (TextUtils.isEmpty(repassword)) {
            Toast.makeText(this, "repassword不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!password.equals(repassword)){
            Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        if(userService.register(phone,password)){
            User user=new User();
            user.setId(userService.getUserByPhone(user.getPhone()).getId());
            user.setPhone(phone);
            user.setPassword(password);
            userService.saveUserBySharedPreferences(user);
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "该手机号已注册", Toast.LENGTH_SHORT).show();
        }
        return;


    }
}
